39A - C++ Calculations - CodeForces Solution


expression parsing greedy *2000

Please click on ads to support us..

Python Code:

from typing import List, Tuple, Optional
from collections import deque, Counter
from queue import PriorityQueue
import math
from functools import lru_cache
import random
import copy
import sys
sys.setrecursionlimit(9999)


MOD = 10**9 + 7



init_a = int(input())
s = input()

n = len(s)
i = 0

ss = ""
while i < n:
    if i+2 <= n-1 and (s[i:i+3] == 'a++' or s[i:i+3] == '++a'):
        ss += "X" if s[i:i+3] == 'a++' else 'Y'
        i += 3
    else:
        ss += s[i]
        i += 1

if ss[0] != '-':
    ss = '+' + ss

arr = []
f = []
n = len(ss)
i = 0
while i < n:
    j = i
    while j+1 < n and (ss[j+1] != 'X' and ss[j+1] != 'Y'):
        j += 1

    if ss[j] == '*':
        v = int(ss[i: j])
        arr.append((v, ss[j+1]))
    else:
        if ss[i] == '-':
            arr.append((-1, ss[j+1]))
        else:
            arr.append((1, ss[j+1]))

    i = j+2


arr.sort()

a = init_a
tot = 0
for v, ch in arr:
    if ch == 'Y':
        a += 1

    tot += a * v

    if ch == 'X':
        a += 1


print(tot)


Comments

Submit
0 Comments
More Questions

450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad
233A - Perfect Permutation
1360A - Minimal Square
467A - George and Accommodation
893C - Rumor
227B - Effective Approach
1534B - Histogram Ugliness
1611B - Team Composition Programmers and Mathematicians
110A - Nearly Lucky Number
1220B - Multiplication Table
1644A - Doors and Keys
1644B - Anti-Fibonacci Permutation
1610A - Anti Light's Cell Guessing
349B - Color the Fence
144A - Arrival of the General